package com.youlu.campus.service.invite.impl;

import com.youlu.campus.entity.UserInviteCount;
import com.youlu.campus.service.invite.UserInviteCountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserInviteCountServiceImpl implements UserInviteCountService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UserInviteCount find(String userId, String activityId, String appId, String platform) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId).and("appId").is(appId).and("platform").is(platform));
        return mongoTemplate.findOne(query, UserInviteCount.class);
    }

    @Override
    public void create(UserInviteCount data) {
        data.setId(null);
        data.setCreatedTime(new Date());
        mongoTemplate.insert(data);
    }

    @Override
    public void increQ(UserInviteCount data) {
        if (Objects.isNull(data) || StringUtils.isBlank(data.getId()) || Objects.isNull(data.getCount())) {
            return;
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(data.getId()));
        Update update = new Update();
        update.inc("count", data.getCount());
        update.set("updatedTime", new Date());
        mongoTemplate.updateFirst(query, update, UserInviteCount.class);
    }

    @Override
    public List<UserInviteCount> list(String userId, String activityId, String appId, String platform, Integer page, Integer pageSize) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId).and("appId").is(appId).and("platform").is(platform));
        query.limit(page);
        query.skip((page - 1) * pageSize);
        query.with(Sort.by(
                Sort.Order.desc("count")
        ));
        return mongoTemplate.find(query, UserInviteCount.class);
    }
}
